import React, { 
  ReactElement, InputHTMLAttributes, FC, ChangeEvent,
  forwardRef,
} from 'react';
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import classNames from 'classnames';

import Icon from '../Icon/icon';

type InputSize = 'lg' | 'sm';

// Omit ts中用于忽略 InputHTMLAttributes 自带的 size 属性
export interface InputProps extends Omit<InputHTMLAttributes<HTMLElement>, 'size'> {
  /**是否禁用 */
  disabled?: boolean;

  /**设置文本框大小 */
  size?: InputSize;

  /**设置图标 */
  icon?: IconProp;

  /**设置文本框前缀 */
  beforefix?: string | ReactElement; // 前缀

  /**设置文本框后缀 */
  afterFix?: string | ReactElement; // 后缀

  width?: number;

  onChange?: (e: ChangeEvent<HTMLInputElement>) => void;
}

/**
 * Input 输入框，通过或键盘输入内容，是最基础的表单域的包装。
 * 
 * ```js
 * // 引用组件
 * import { Input } from 'rqx-ui'
 * ```
 * 支持 HTMLInput 的所有基本属性
 */
export const Input: FC<InputProps> = forwardRef((props, ref) => {
  const {
    disabled,
    size,
    icon,
    beforefix,
    afterFix,
    style,
    width,
    ...rest
  } = props;

  const cnames = classNames('input-wrapper', {
    [`input-size-${size}`]: size,
    'is-disabled': disabled,
    'input-group': beforefix || afterFix,
    'input-group-afterFix': !!afterFix,
    'input-group-beforefix': !!beforefix
  });

  // 避免 input 值为 undefied
  const controlledValue = (value: any) => {
    if (typeof value === 'undefined' || value === null) {
      return '';
    }
    return value;
  };

  if('value' in props) {
    delete rest.defaultValue;
    rest.value = controlledValue(props.value);
  }

  return (
    <div className={cnames} style={{...style, width: `${width}px`}}>
      {beforefix && <div className="input-group-beforefix">{beforefix}</div>}
      {icon && <div className="icon-wrapper"><Icon icon={icon} title={`title-${icon}`}/></div>}
      <input 
        className="input-inner"
        disabled={disabled}
        {...rest}
      />
      {afterFix && <div className="input-group-afterFix">{afterFix}</div>}
    </div>
  )
});

export default Input;